package com.oocl.userinfo.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.oocl.userinfo.dao.UserDao;
import com.oocl.userinfo.pojo.User;
import com.oocl.userinfo.util.DBUtil;

public class UserDaoImpl implements UserDao {

	@Override
	public int addUser(User u) {
		String sql = "insert into netusers(id, uname, sal, birth, sex, head) values(netuser_id_seq.nextval, ?, ?, ?, ?, ?)";
		Connection connection = null;
		PreparedStatement pst = null;
		int count = 0;
		try {
			connection = DBUtil.createConnection();
			pst = connection.prepareStatement(sql);
			pst.setString(1, u.getUname());
			pst.setDouble(2, u.getSal());
			pst.setDate(3, new java.sql.Date(u.getBirth().getTime()));
			pst.setBoolean(4, u.getSex());
			pst.setBytes(5, u.getHead());
			count = pst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			DBUtil.close(connection, pst, null);
		}
		return count;
	}

	@Override
	public List<User> findAll() {
		List<User> list = new ArrayList<User>();
		
		String sql="select * from netusers";
		Connection connection = null;
		PreparedStatement pst=null;
		try {
			connection = DBUtil.createConnection();
			pst = connection.prepareStatement(sql);
			ResultSet rs = null;
			rs=pst.executeQuery();
			
			while(rs.next()){
				User user = new User();
				user.setUname(rs.getString("uname"));
				user.setSal(rs.getDouble("sal"));
				user.setBirth(new java.util.Date(rs.getDate("birth").getTime()));
				user.setSex(rs.getBoolean("sex"));
				user.setHead(rs.getBytes("head"));
				list.add(user);
			}
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
			return list;
		} finally{
			DBUtil.close(connection, pst, null);
		}
	}

}
